Ext.define('jwawa.erp.cfg.searchPage.SearchPageDetailHandler', {
    extend: 'jwawa.erp.framework.ShellHandler',
    mixins: {
        searchItemHelper: 'jwawa.erp.cfg.searchPage.SearchItemHelper'
    },
    searchItemWin: null,
    entityHeaderId: null,
    entities: ['cfg_search_pages', 'cfg_search_items'],
    resources: [
        {
            name: 'searchPageModel',
            res: 'jwawa.erp.cfg.searchPage.SearchPageModel'
        },
        {
            name: 'searchItemModel',
            res: 'jwawa.erp.cfg.searchPage.SearchItemModel'
        },
        {
            name: 'entityHeaderModel',
            res: 'jwawa.erp.cfg.entity.EntityHeaderModel'
        },
        {
            name: 'entityDetailModel',
            res: 'jwawa.erp.cfg.entity.EntityDetailModel'
        },
        {
            name: 'actionModel',
            res: 'jwawa.erp.cfg.action.ActionModel'
        },
        {
            name: 'actionStore',
            res: '',
            type: 'store',
            cfg: {
                fields: [
                    {name: 'id',  type: 'int'},
                    'action_code'
                ],
                autoLoad: false
            }
        },
        {
            name: 'entityHeaderStore',
            res: '',
            type: 'store',
            cfg: {
                fields: [
                    {name: 'id',  type: 'int'},
                    'entity_code'
                ],
                autoLoad: false
            }
        },
        {
            name: 'entityDetailStore',
            type: 'store',
            cfg:{
                fields: [
                    {name: 'id',  type: 'int'},
                    'entity_field_name',
                    'entity_field_label'
                ],
                autoLoad: false
            }
        },
        {
            name: 'searchItemStore',
            type: 'store',
            cfg:{
                fields: [
                    {name: 'id',  type: 'int'},
                    {name: 'page_id',  type: 'int'},
                    {name: 'entity_detail_id',  type: 'int'},
                    'entity_field_name',
                    'entity_field_label',
                    'item_name',
                    'item_label',
                    'item_type',
                    'item_class',
                    'condition_flag',
                    'item_cfg',
                    {name: 'seq',  type: 'int'}
                ],
                autoLoad: false,
                sorters: [{property: 'seq', direction: 'ASC'}]
            }
        }
    ],
    ref:{
        searchPageDetailPanel: '#searchPageDetailPanel',
        searchPageFormPanel: '#searchPageFormPanel',
        searchItemGridPanel: '#searchItemGridPanel',

        pageIdField: '#pageIdField',
        pageNameField: '#pageNameField',

        actionCombobox: '#actionCombobox',
        entityCombobox: '#entityCombobox',
        saveSearchPageButton: '#saveSearchPageButton',
        delSearchPageButton: '#delSearchPageButton',
        newSearchPageButton: '#newSearchPageButton',
        returnButton: '#returnButton',
        refreshButton: '#refreshButton',

        editSearchItemButton: '#editSearchItemButton',
        newSearchItemButton: '#newSearchItemButton',
        delSearchItemButton: '#delSearchItemButton',
        goUpItemButton: '#goUpItemButton',
        goDownItemButton: '#goDownItemButton',
        goTopItemButton: '#goTopItemButton',
        goBottomItemButton: '#goBottomItemButton'
    },
    bindHandler: function(){
        "use strict";
        var me = this,
            searchItemModel = Ext.JwawaResMgr.get('searchItemModel'),
            entityHeaderModel = Ext.JwawaResMgr.get('entityHeaderModel');

        me.view.addListener('render', me.onRenderSearchPageDetailShell, me);
        me.view.addListener('pageStateChange', me.onPageStateChange, me);
        searchItemModel.addListener('saveSearchItem', me.onSaveSearchItem, me);

        me.searchItemWin = find_or_create_win('jwawa.erp.cfg.searchPage.SearchItemShell',
            {modal: true}
        );

        me.initSearchPageFormPanel();
        me.initSearchItemGridPanel();

        me.view.setPageState('initPage');
    },

    onRenderSearchPageDetailShell: function(){
        "use strict";
        var me = this,
            entityHeaderModel = Ext.JwawaResMgr.get('entityHeaderModel'),
            entityHeaderStore = Ext.JwawaResMgr.get('entityHeaderStore'),
            actionModel = Ext.JwawaResMgr.get('actionModel'),
            actionStore = Ext.JwawaResMgr.get('actionStore');

        entityHeaderModel.findAllEntities({
                success: function(entities){
                    entityHeaderStore.loadData(entities);
                }
        });

        actionModel.findAllLeafActions({
            success: function(actions){
                actionStore.loadData(actions);
            }
        });

    },

    initSearchPageFormPanel: function(){
        "use strict";
        var me = this,
            entityHeaderStore = Ext.JwawaResMgr.get('entityHeaderStore'),
            actionStore = Ext.JwawaResMgr.get('actionStore');

//        me.searchPageFormPanel.getForm().url = '/search-page/save-search-page';
        me.entityCombobox.bindStore(entityHeaderStore);
        me.actionCombobox.bindStore(actionStore);

        me.saveSearchPageButton.on('click', me.onClickSaveSearchPageButton, this);
        me.delSearchPageButton.on('click', me.onClickDelSearchPageButton, this);
        me.newSearchPageButton.on('click', me.onClickNewSearchPageButton, this);
        me.returnButton.on('click', me.onClickReturnButton, this);
        me.refreshButton.on('click', me.onClickRefreshButton, this);

        me.searchPageFormPanel.addListener('afterRender', function(){
            fieldKeyNavBind('#searchPageFormPanel', me.onClickSaveSearchPageButton, me);
        });
    },

    onClickRefreshButton: function(){
        "use strict";
        var me = this,
            pageId,
            form = me.searchPageFormPanel.getForm();

        pageId = parseInt(form.findField('id').getValue());
        me.editPageContent(pageId);
    },

    onClickSaveSearchPageButton: function(){
        "use strict";
        var me = this,
            searchPageModel = Ext.JwawaResMgr.get('searchPageModel'),
            searchPageStore = Ext.JwawaResMgr.get('searchPageStore'),
            entityDetailModel = Ext.JwawaResMgr.get('entityDetailModel'),
            entityDetailStore = Ext.JwawaResMgr.get('entityDetailStore');

//        var searchPage = me.searchPageFormPanel.getForm().getValues(false, false, false, false);


        if(me.entityCombobox.getValue() != me.entityHeaderId &&
                !Ext.isEmpty(me.entityHeaderId)){
            alertConfirm('提示', '由于修改了实体选项，保存后明细将被清空，请确认是否继续保存？', function(){
                me.saveSearchPage(true);
            })
        }else{
            me.saveSearchPage(false);
        }
    },

    saveSearchPage: function(needCleanSearchItem){
        "use strict";
        var me = this,
            searchPageModel = Ext.JwawaResMgr.get('searchPageModel'),
            searchPageStore = Ext.JwawaResMgr.get('searchPageStore'),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore'),
            entityDetailModel = Ext.JwawaResMgr.get('entityDetailModel'),
            entityDetailStore = Ext.JwawaResMgr.get('entityDetailStore'),
            form = me.searchPageFormPanel.getForm();

        if(form.isValid()){
            me.view.setLoading(true);
            var searchPage = form.getValues();
            searchPageModel.saveSearchPage(searchPage, {
                success: function(searchPage) {
                    var searchPageRecord = searchPageStore.getById(searchPage['id']);
                    me.entityHeaderId = searchPage['entity_header_id'];
                    if(!Ext.isEmpty(searchPageRecord)){
                        searchPageRecord.set('page_name', searchPage['page_name']);
                        searchPageRecord.set('page_code', searchPage['page_code']);
                        searchPageRecord.commit();
                    }

                    form.setValues(searchPage);
                    me.view.setPageState('editPage');

                    if(needCleanSearchItem){
                        searchItemStore.removeAll();
                    }
                    if(Ext.isEmpty(searchPage['entity_header_id'])){
                        entityDetailStore.removeAll();
                    }else{
                        var entityDetailList = entityDetailModel.findEntityDetailListByHeaderId(me.entityCombobox.getValue());
                        entityDetailStore.loadData(entityDetailList);
                    }
                    top.msgBar.showSuccessMsg('检索页基本信息保存成功');
                    me.view.setLoading(false);
                },
                failure: function(){
                    me.view.setLoading(false);
                }
            });
        }
    },

    onClickDelSearchPageButton: function(){
        "use strict";
        var me = this,
            form = me.searchPageFormPanel.getForm(),
            pageId = parseInt(form.findField('id').getValue()),
            searchPageModel = Ext.JwawaResMgr.get('searchPageModel'),
            searchPageStore = Ext.JwawaResMgr.get('searchPageStore');

        alertConfirm('提示','真的要执行删除操作吗？', function(buttonId){
            if(buttonId == 'yes'){
                if(pageId){
                    me.view.setLoading(true);
                    searchPageModel.deleteSearchPage([pageId], {
                        success : function(pageIds) {
                            var searchPageQueryPanel = me.view.previousSibling('#searchPageQueryPanel'),
                                searchPage = searchPageStore.getById(pageId);

                            searchPageStore.remove(searchPage);
                            me.clearPageContent();
                            me.view.setPageState('delPage');
                            top.msgBar.showSuccessMsg('删除指定检索页记录成功');
                            searchPageQueryPanel.show();
                        },
                        callback: function(){
                            me.view.setLoading(false);
                        }
                    });
                }
            }
        });
    },

    onClickNewSearchPageButton: function(){
        "use strict";
        var me = this;

        me.newPageContent();
    },

    onClickReturnButton: function(){
        "use strict";
        var me = this,
            searchPageQueryPanel = me.view.previousSibling('#searchPageQueryPanel');

        me.clearPageContent();
        me.view.setPageState('initPage');
        searchPageQueryPanel.show();
    },

    clearPageContent: function(){
        "use strict";
        var me = this,
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore');

        me.entityHeaderId = null;
        me.searchPageFormPanel.getForm().reset();
        searchItemStore.removeAll();
    },

    newPageContent: function(){
        "use strict";
        var me = this;

        me.clearPageContent();
        me.view.setPageState('newPage');
        me.view.show();
    },

    editPageContent: function(pageId){
        "use strict";
        var me = this,
            searchPageModel = Ext.JwawaResMgr.get('searchPageModel'),
            searchItemModel = Ext.JwawaResMgr.get('searchItemModel'),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore'),
            entityDetailModel = Ext.JwawaResMgr.get('entityDetailModel'),
            entityDetailStore = Ext.JwawaResMgr.get('entityDetailStore');

        me.clearPageContent();
        me.view.show();
        me.view.setLoading(true);
        searchPageModel.getSearchPageAndItem(pageId, {
            success: function(searchPage, searchItemList){
                var form = me.searchPageFormPanel.getForm();

                me.entityHeaderId = searchPage['entity_header_id'];
                form.setValues(searchPage);
                searchItemStore.loadRawData(searchItemList);
                me.pageNameField.focus(true, DEFAULT_FOCUS_DEFER_TIME);
                me.view.setPageState('editPage');

                if(Ext.isEmpty(searchPage['entity_header_id'])){
                    entityDetailStore.removeAll();
                }else{
                    var entityDetailList = entityDetailModel.findEntityDetailListByHeaderId(me.entityCombobox.getValue());
                    entityDetailStore.loadData(entityDetailList);
                }

                me.view.show();
            },
            failure: function(){
                me.view.setPageState('initPage');
            },
            callback: function(){
                me.view.setLoading(false);
            }
        });
    },

    initSearchItemGridPanel: function(){
        "use strict";
        var me = this,
            searchItemModel = Ext.JwawaResMgr.get('searchItemModel'),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore');
            me.searchItemGridPanel.reconfigure(searchItemStore);

        // 监听GridItem选择事件
        var searchItemSm = me.searchItemGridPanel.getSelectionModel();
        searchItemSm.on('selectionchange', me.onSelectChangeSearchItem, me);
        me.searchItemGridPanel.on('itemdblclick', me.onItemDbClickSearchItem, this);

        me.editSearchItemButton.on('click', me.onClickEditSearchItemButton, this);
        me.newSearchItemButton.on('click', me.onClickNewSearchItemButton, this);
        me.delSearchItemButton.on('click', me.onClickDelSearchItemButton, this);
        me.goUpItemButton.on('click', me.onClickGoUpItemButton, this);
        me.goDownItemButton.on('click', me.onClickGoDownItemButton, this);
        me.goTopItemButton.on('click', me.onClickGoTopItemButton, this);
        me.goBottomItemButton.on('click', me.onClickGoBottomItemButton, this);
    },
    onItemDbClickSearchItem: function( obj, record, item, index, e, eOpts ){
        "use strict";
        var me = this;

        me.editSearchItem(record.data);
    },

    onSelectChangeSearchItem: function(obj, selected, eOpts){
        "use strict";
        var me = this;

        me.view.setPageState('deselectItem');
        if(selected.length > 0){
            me.view.setPageState('selectItem');
        }
    },

    onClickEditSearchItemButton: function(){
        "use strict";
        var me = this,
        searchItemSm = me.searchItemGridPanel.getSelectionModel(),
        searchItem = searchItemSm.getSelection()[0];
        me.editSearchItem(searchItem.data);
    },

    editSearchItem: function(searchItem){
        "use strict";
        var me = this,
            searchItemShell = me.searchItemWin.down('cfgSearchItemShell'),
            pageId = me.pageIdField.getValue(),
            pageName = me.pageNameField.getValue(),
            entityHeaderId = me.entityCombobox.getValue();

        showWindow(me.searchItemWin, true);
        searchItemShell.handler.editSearchItem(searchItem, pageId, pageName, entityHeaderId);
    },

    onClickNewSearchItemButton: function(){
        "use strict";
        var me = this,
            searchItemShell = me.searchItemWin.down('cfgSearchItemShell'),
            pageId = me.pageIdField.getValue(),
            pageName = me.pageNameField.getValue(),
            entityHeaderId = me.entityCombobox.getValue();

        showWindow(me.searchItemWin, true);

        searchItemShell.handler.newSearchItem(pageId, pageName, entityHeaderId);
    },

    onSaveSearchItem: function(obj, searchItem){
        "use strict";
        var me = this,
            searchItemSm = me.searchItemGridPanel.getSelectionModel();

        searchItemSm.deselectAll();
    },

    onClickDelSearchItemButton: function(){
        "use strict";
        var me = this,
            searchItemModel = Ext.JwawaResMgr.get('searchItemModel'),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore'),
            searchItemSm = me.searchItemGridPanel.getSelectionModel(),
            curItem = searchItemSm.getSelection()[0];

        alertConfirm('提示','真的要执行删除操作吗？', function(buttonId){
            if(buttonId == 'yes'){
                me.view.setLoading(true);
                searchItemModel.delSearchItem(curItem.get('id'), function(itemId){
                    me.afterDelSerchItem(itemId);
                    me.view.setLoading(false);
                });
            }
        });
    },

    onClickGoTopItemButton: function(){
        "use strict";
        var me = this;

        me.changeSearchItemSeq('top');
    },

    onClickGoUpItemButton: function(){
        "use strict";
        var me = this;

        me.changeSearchItemSeq('up');
    },

    onClickGoDownItemButton: function(){
        "use strict";
        var me = this;

        me.changeSearchItemSeq('down');
    },

    onClickGoBottomItemButton: function(){
        "use strict";
        var me = this;

        me.changeSearchItemSeq('bottom');
    },

    changeSearchItemSeq: function(optFlag){
        "use strict";
        var me = this,
            searchItemSm = me.searchItemGridPanel.getSelectionModel(),
            curItem = searchItemSm.getSelection()[0],
            searchItemModel = Ext.JwawaResMgr.get('searchItemModel'),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore');

        me.view.setPageState('initItem');
        searchItemModel.changeSearchItemSeq(curItem, optFlag, {
            success: function(){
                var idx = searchItemStore.indexOf(curItem),
                    searchItems,
                    preSearchItem,
                    nextSearchItem,
                    lastItem,
                    maxSeq,
                    lastIdx;

                switch(optFlag){
                    case 'top':
                        searchItems = searchItemStore.getRange(0, idx - 1);
                        Ext.each(searchItems, function(searchItem){
                            searchItem.set('seq', searchItem.get('seq') + 1);
                            searchItem.commit();
                        });
                        curItem.set('seq', 1);
                        curItem.commit();
                        searchItemStore.sort();
                        break;

                    case 'up':
                        preSearchItem = searchItemStore.getAt(idx - 1);
                        preSearchItem.set('seq', preSearchItem.get('seq') + 1);
                        preSearchItem.commit();
                        curItem.set('seq', curItem.get('seq') - 1);
                        curItem.commit();
                        searchItemStore.sort();
                        break;

                    case 'down':
                        nextSearchItem = searchItemStore.getAt(idx + 1);
                        nextSearchItem.set('seq', nextSearchItem.get('seq') - 1);
                        nextSearchItem.commit();
                        curItem.set('seq', curItem.get('seq') + 1);
                        curItem.commit();
                        searchItemStore.sort();
                        break;

                    case 'bottom':
                        lastItem = searchItemStore.last();
                            maxSeq = lastItem.get('seq');
                            lastIdx = searchItemStore.indexOf(lastItem);

                        if(lastIdx >= idx + 1){
                            searchItems = searchItemStore.getRange(idx + 1, lastIdx);
                            Ext.each(searchItems, function(searchItem){
                                searchItem.set('seq', searchItem.get('seq') - 1);
                                searchItem.commit();
                            });

                            curItem.set('seq', maxSeq);
                            curItem.commit();
                            searchItemStore.sort();
                        }
                        break;
                }
            },
            callback: function(){
                me.view.setPageState('deselectItem');
                me.view.setPageState('selectItem');
            }
        });
    },

    onPageStateChange: function(obj, state){
        "use strict";
        var me = this,
            searchItemSm = me.searchItemGridPanel.getSelectionModel(),
            searchItemStore = Ext.JwawaResMgr.get('searchItemStore');

        switch(state){
            case 'delPage':
            case 'initPage':
                me.searchPageDetailPanel.disable();

                me.saveSearchPageButton.disable();
                me.delSearchPageButton.disable();
                me.newSearchPageButton.enable();
                me.refreshButton.disable();
                me.returnButton.enable();

                me.onPageStateChange(me, 'initItem');
                break;
            case 'newPage':
                me.searchPageDetailPanel.enable();

                me.saveSearchPageButton.enable();
                me.delSearchPageButton.disable();
                me.newSearchPageButton.enable();
                me.refreshButton.disable();
                me.returnButton.enable();

                me.onPageStateChange(me, 'initItem');
                break;
            case 'editPage':
                me.searchPageDetailPanel.enable();

                me.saveSearchPageButton.enable();
                me.delSearchPageButton.enable();
                me.newSearchPageButton.enable();
                me.refreshButton.enable();
                me.returnButton.enable();

                me.onPageStateChange(me, 'initItem');
                me.newSearchItemButton.enable();
                break;
            case 'initItem':
                me.editSearchItemButton.disable();
                me.newSearchItemButton.disable();
                me.delSearchItemButton.disable();

                me.goUpItemButton.disable();
                me.goDownItemButton.disable();
                me.goTopItemButton.disable();
                me.goBottomItemButton.disable();
                break;
            case 'selectItem':
                me.editSearchItemButton.enable();
                me.delSearchItemButton.enable();

                var lastItem = searchItemStore.last(),
                    firstItem = searchItemStore.first(),
                    curItem = searchItemSm.getSelection()[0],
                    count = searchItemStore.count();

                if(count > 1){
                    if(curItem.get('id') == firstItem.get('id')){
                        me.goDownItemButton.enable();
                        me.goBottomItemButton.enable();
                    }else if(curItem.get('id') == lastItem.get('id')){
                        me.goUpItemButton.enable();
                        me.goTopItemButton.enable();
                    }else{
                        me.goUpItemButton.enable();
                        me.goDownItemButton.enable();
                        me.goTopItemButton.enable();
                        me.goBottomItemButton.enable();
                    }
                }

                break;
            case 'deselectItem':
                me.editSearchItemButton.disable();
                me.delSearchItemButton.disable();

                me.goUpItemButton.disable();
                me.goDownItemButton.disable();
                me.goTopItemButton.disable();
                me.goBottomItemButton.disable();
                break;
        }
    }
});